<?php
/**
 * User: sunxiaozhi
 * Date: 2018/9/15
 * Time: 21:49
 */

namespace backend\models;

use Yii;
use common\models\ArticleTag;
use common\models\ArticleTagRelation;

class Article extends \common\models\Article
{
    /**
     * 执行保存标签的操作
     * @param bool $insert
     * @param array $changedAttributes
     * @throws \yii\base\InvalidConfigException
     */
    public function afterSave($insert, $changedAttributes)
    {
        $articleId = $this->id;

        if (Yii::$app->request->isPost) {
            $formArticle = Yii::$app->request->post('Article');

            if (isset($formArticle['tag'])) {
                $tagArr = explode(',', $formArticle['tag']);

                //清除所有的文章和标签的关系
                $ArticleTagRelation = new ArticleTagRelation();
                $ArticleTagRelation::deleteAll(['article_id' => $articleId]);

                //依次添加文章和标签的关系
                foreach ($tagArr as $key => $val) {
                    if (!empty($val)) {
                        $articeleTagData = ArticleTag::find()->where(['name' => $val])->one();

                        //标签不存在，则添加
                        if (empty($articeleTagData)) {
                            $articeleTag = new ArticleTag();
                            $articeleTag->name = $val;
                            $articeleTag->alias = $val;
                            $articeleTag->save();

                            $tagId = $articeleTag->id;
                        } else {
                            $tagId = $articeleTagData->id;
                        }
                    } else {
                        continue;
                    }

                    $ArticleTagRelation = new ArticleTagRelation();
                    $ArticleTagRelation->article_id = $articleId;
                    $ArticleTagRelation->tag_id = $tagId;
                    $ArticleTagRelation->save();
                }
            }
        }

        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
    }
}